package com.sc.web.gwt.server.persistence;

import java.sql.*;

public abstract class AbstractDBConnection {
    private Connection connection = null;
    private String url = "jdbc:mysql://localhost/authenticationdatabase";
    private String driver = "com.mysql.jdbc.Driver";
    private String userName = "root";
    private String password = "123456789";

    protected Connection getConnection() {
        try {
            Class.forName(driver).newInstance();
            connection = DriverManager.getConnection(url, userName, password);
        } catch (Exception e) {
            System.err.println("MySQL Error: ");
            e.printStackTrace();
        }

        if (connection == null) {
            System.out.println("Cannot get Mysql connection");
        }

        return connection;
    }

    /*
    * get recordset row count
    *
    * static will allow you to use it independently, persay,
    * you don't have to init the class into an object to use this method
    */
    protected static int getResultSetSize(ResultSet resultSet) {
        int size = -1;

        try {
            resultSet.last();
            size = resultSet.getRow();
            resultSet.beforeFirst();
        } catch (SQLException e) {
            return size;
        }

        return size;
    }

    //if return -1 means there is an error
    protected int getLastId() {
        String getLastIdQuery = "select LAST_INSERT_ID()";

        int id = -1;
        try {
            Connection connection = getConnection();
            Statement stmt = connection.createStatement();
            ResultSet rs = stmt.executeQuery(getLastIdQuery);
            connection.close();

            if (rs.next()) {
                id = rs.getInt(1);
            }
        } catch (Exception e) {
            System.err.println("Mysql Statement Error: " + getLastIdQuery);
            e.printStackTrace();
            return id;
        }

        return id;
    }

}
